<template>
  <div class="app-container">
    <FileExplorer @file-content-update="updateContent" />
    <div class="editor-section">
      <div class="editor-container">
        <div class="line-numbers">
          <div v-for="n in lineCount" :key="n" class="line-number">{{ n }}</div>
        </div>
        <textarea
          v-model="fileContent"
          class="content-viewer"
          @input="updateLineCount"
        ></textarea>
      </div>
      <button class="save-button" @click="handleSave">保存</button>
    </div>
  </div>
</template>

<script setup>
import FileExplorer from './components/FileExplorer.vue'
import { ref, onMounted } from 'vue'

const fileContent = ref('')
const lineCount = ref(1)
const currentFilePath = ref('')

const updateContent = (data) => {
  fileContent.value = data.content
  currentFilePath.value = data.path
  updateLineCount()
}

const updateLineCount = () => {
  lineCount.value = fileContent.value.split('\n').length
}

const handleSave = async () => {
  try {
    const response = await fetch('/api/v1/fs/save', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        path: currentFilePath.value,
        content: fileContent.value
      })
    })
    
    if (!response.ok) {
      throw new Error('保存失败')
    }
    
    alert('保存成功')
  } catch (error) {
    console.error('保存文件失败:', error)
    alert('保存失败：' + error.message)
  }
}

onMounted(() => {
  updateLineCount()
})
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
}

.app-container {
  display: flex;
  height: 100vh;
  gap: 20px;
  padding: 20px;
}

.editor-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.editor-container {
  flex: 1;
  display: flex;
  border: 1px solid #eee;
}

.save-button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;

  &:hover {
    background-color: #45a049;
  }
}

.line-numbers {
  padding: 10px 8px;
  background-color: #f5f5f5;
  border-right: 1px solid #eee;
  user-select: none;
}

.line-number {
  font-family: monospace;
  color: #999;
  text-align: right;
  font-size: 14px;
  line-height: 1.5;
}

.content-viewer {
  flex: 1;
  min-height: 500px;
  padding: 10px;
  border: none;
  font-family: monospace;
  resize: none;
  font-size: 14px;
  line-height: 1.5;
}
</style>
